<?php

namespace App\Http\Controllers\Api;


use App\Models\Api\SalesStrategy;
use App\Models\Api\Address;
use App\Models\Api\Express;
use App\Models\Api\GoodsStore;
use App\Models\Api\Store;
use App\Models\Api\StoreCart;
use App\Models\Api\StoreOrder;
use App\Models\Api\StoreOrderGoods;
use App\Tools\Financial;
use App\Tools\PrPdf;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use App\Models\Api\Goods;
use Illuminate\Support\Facades\DB;

class OrderController extends BaseController
{

    /**
     * 购物车
     */
    public function shoppingCart()
    {
        $store_id = $this->userArr['store_id'];
        $list = StoreCart::getListBySid($store_id);
        successMsg($list);
    }

    /**
     * 添加购物车
     */
    public function upShoppingCart()
    {
        $id = $this->requestArr['id'] ?: 0;
        $num = $this->requestArr['num'] ?: 0;
        $type= $this->requestArr['type'] ?: 1;

        $store_id = $this->userArr['store_id'];
        if ($id && $num > 0) {
            StoreCart::where(['store_id' => $store_id, 'id' => $id, 'type' => $type])->update(['goods_num' => $num]);
            successMsg();
        }

        errorMsg();
    }

    /**
     * 添加购物车
     */
    public function delShoppingCart()
    {
        $id = $this->requestArr['id'] ?: 0;
        $store_id = $this->userArr['store_id'];
        if ($id) {
            $ids = explode(',', $id);
            if ($ids) {
                StoreCart::whereIn('id', $ids)->where(['store_id' => $store_id])->delete();
                StoreCart::whereIn('goods_pid', $ids)->where(['store_id' => $store_id])->delete();
                successMsg();
            }
        }
        errorMsg();
    }

    /**
     * 订单提交页
     */
    public function orderSubmit()
    {
        $store_id = $this->userArr['store_id'];
        # 补货权限
        $is_replenishment = Store::where(['id' => $store_id])->value('is_replenishment');
        if ($is_replenishment == 0) {
            errorMsg('暂无补货权限，请联系客服');
        }
        $ids = $this->requestArr['ids'];
        $goods_id = $this->requestArr['goods_id'];
        $goods_num = $this->requestArr['goods_num'] ?: 0;
        $express_fee = 0;
        if ($goods_id || $ids) {
            if ($goods_id) {
                if ($goods_num < 1) {
                    errorMsg('数量错误');
                }
                $goodsInfo = GoodsStore::getOrderByGoodsId($store_id, $goods_id, $goods_num);
                if (!$goodsInfo) {
                    errorMsg('商品错误错误');
                }
                $goods_num = $goods_num < $goodsInfo['mini_quantity'] ? $goodsInfo['mini_quantity'] : $goods_num;
                $ids[] = $goods_id;
            } elseif ($ids) {
                if (is_numeric($ids)) {
                    $ids = [$ids];
                } else {
                    $ids = explode(',', $ids);
                }
            }
            # 购物车数据
            $cartArr = SalesStrategy::getAllGoodsList($store_id, $ids, $goods_num);
            $num = $cartArr['goodsNum'];
            $money = $cartArr['goodsMoney'];
            # 地址物流信息
            $express = Express::getAllList();
            $address = Address::getDefaultBySId($store_id);
            // 新的运费计算方式
            $result = $this->calcAmountByGoodsList($cartArr['goods_list'], $express[0], $address['province'], $store_id);
            if (isset($result['error'])) {
                errorMsg($result['error']);
            } else {
                $express_fee = $result['freight'];
            }
            $info['goods_list'] = $cartArr['goods_list'];
            $info['goods_give_list'] = $cartArr['goods_give_list'];
            $info['pay_num'] = $cartArr['goodsNum'];
            $info['num'] = $cartArr['totalNum'];
            $info['goods_money'] = $money;
            $info['total_money'] = $money + $express_fee;
            $info['express'] = $express;
            $info['address'] = $address;
            $info['express_fee'] = $express_fee;
            # 商户资金信息
            $info['hk_money'] = Financial::getInfoByAid($store_id, 1, 1, 'money');
            $info['gl_money'] = Financial::getInfoByAid($store_id, 1, 2, 'money');
            successMsg($info);
        }
        errorMsg();
    }

    /**
     * 动态获取运费
     */
    public function freightAndAmount()
    {
        $store_id = $this->userArr['store_id'];

        // 权限检查
        $is_replenishment = Store::where(['id' => $store_id])->value('is_replenishment');
        if ($is_replenishment == 0) {
            errorMsg('暂无补货权限，请联系客服');
        }

        // 接收参数
        $express_id = $this->requestArr['express_id'];
        $address_id = $this->requestArr['address_id'];
        $ids = $this->requestArr['ids'] ?? [];
        $goods_id = $this->requestArr['goods_id'] ?? null;
        $goods_num = $this->requestArr['goods_num'] ?? 0;

        if (!$goods_id && empty($ids)) {
            errorMsg('缺少商品信息');
        }

        // 组装商品信息
        $goods_info_arr = [];
        $goods_give_list = []; // 新增：赠品商品列表
        if ($goods_id) {
            if ($goods_num < 1) {
                errorMsg('数量错误');
            }
            $goods_info_arr[] = ['goods_id' => $goods_id, 'goods_num' => $goods_num];
        }

        if ($ids) {
            if (is_numeric($ids)) {
                $ids = [$ids];
            } else {
                $ids = explode(',', $ids);
            }
            // 获取购物车商品
            $cartArr = SalesStrategy::getAllGoodsList($store_id, $ids, 0);
            $goods_list = $cartArr['goods_list'];
            foreach ($goods_list as $item) {
                // 根据is_give判断是普通商品还是赠品
                if (isset($item['is_give']) && $item['is_give'] == 1) {
                    $goods_give_list[] = [
                        'goods_id' => $item['goods_id'],
                        'type' => $item['type'],
                        'goods_weight_m' => $item['goods_weight_m'] ?? 0, // 重量字段
                        'goods_num' => $item['goods_num'],
                        'goods_pid' => $item['goods_pid'] ?? 0 // 保留goods_pid信息
                    ];
                } else {
                    $goods_info_arr[] = [
                        'goods_id' => $item['goods_id'],
                        'type' => $item['type'],
                        'goods_weight_m' => $item['goods_weight_m'] ?? 0, // 重量字段
                        'goods_num' => $item['goods_num'],
                        'goods_pid' => $item['goods_pid'] ?? 0 // 保留goods_pid信息
                    ];
                }
            }
        }

        // 地址和省份
        $address = Address::getInfoById($address_id, $store_id);
        if (!$address) {
            errorMsg('地址错误');
        }
        $province = $address['province'] ?? '';
        if (empty($province)) {
            errorMsg('未找到默认省份');
        }

        // 获取快递公司信息
        $express = Express::getInfoById($express_id);
        if (!$express) {
            errorMsg('快递公司不存在');
        }
        // 获取折扣
//        $discount_rate = \App\Models\Admin\Store::where(['id' => $store_id])->value('discount_rate') ?? 1;
        // 调用统一计算逻辑
        $result = $this->calcAmountByGoodsList($goods_info_arr, $express, $province, $store_id);

        if (isset($result['error'])) {
            errorMsg($result['error']);
        }

        $order_amount = $result['order_amount'];
        $freight = $result['freight'];
        $goods_list = $result['goods_list'];
        $num = $result['num'];
        $original_amount = $result['original_amount'] ?? 0;

        // 返回数据
        $info = [
            'goods_list' => $goods_list,
            'goods_give_list' => $goods_give_list, // 使用收集的赠品列表
            'pay_num' => count($goods_list),
//            'num' => array_sum(array_column($goods_list, 'goods_num')),
            'num' => $num,
            'goods_money' => $order_amount,
            'total_money' => $original_amount,
            'original_money' => $original_amount,
            'express' => Express::getAllList(),
            'address' => $address,
            'express_fee' => round($freight, 2),
            'discount_rate' => $result['discount_rate'],
            'hk_money' => Financial::getInfoByAid($store_id, 1, 1, 'money'),
            'gl_money' => Financial::getInfoByAid($store_id, 1, 2, 'money')
        ];

        successMsg($info);
    }


    /**
     * 生成订单  发货订单
     */
    public function orderMake()
    {
        $store_id = $this->userArr['store_id'];
        # 补货权限 发货订单权限
        $storeInfo = Store::where(['id' => $store_id])->select(['discount_rate', 'is_replenishment', 'avoid_review_amount', 'avoid_review_start_time', 'avoid_review_end_time'])->first();
        if ($storeInfo->is_replenishment == 0) {
            errorMsg('暂无补货权限，请联系客服');
        }
        $pamas = $this->requestArr;
        $ids = $this->requestArr['ids'];
        if (!$pamas['address_id']) {
            errorMsg('请填写地址');
        }
        if (!$pamas['express_id']) {
            errorMsg('请选择快递');
        }
        $address = Address::getInfoById($pamas['address_id'], $store_id);
        if (!$address) {
            errorMsg('地址错误');
        }
        $pamas['order_name'] = $address['name'];
        $pamas['order_mobile'] = $address['mobile'];
        $pamas['order_province'] = $address['province'];
        $pamas['order_city'] = $address['city'];
        $pamas['order_area'] = $address['area'];
        $pamas['order_address'] = $address['address'];
        $goods_id = $this->requestArr['goods_id'];
        $goods_num = $this->requestArr['goods_num'] ?: 0;
        if ($goods_id || $ids) {
            $express_fee = 0;
            if ($goods_id) {
                if ($goods_num < 1) {
                    errorMsg('数量错误');
                }
                $goodsInfo = GoodsStore::getOrderByGoodsId($store_id, $goods_id);
                if (!$goodsInfo) {
                    errorMsg('商品错误错误');
                }
                $ids[] = $goods_id;
            } elseif ($ids) {
                if (is_numeric($ids)) {
                    $ids = [$ids];
                } else {
                    $ids = explode(',', $ids);
                }
                $pamas['ids'] = $ids;
                // 获取购物车商品
                $cartArr = SalesStrategy::getAllGoodsList($store_id, $ids, 0);
                $goods_list = $cartArr['goods_list'];
                $goodsIds = [];
                foreach ($goods_list as $key=>$item) {
                    $goodsIds[$key] =  $item['goods_id'];
                }
            }

            # 购物车数据
            $cartArr = SalesStrategy::getAllGoodsList($store_id, $ids, $goods_num);
            // 检查组合商品库存
            foreach ($cartArr['goods_list'] as $item) {
                $goods = Goods::find($item['goods_id']);
                if (!$goods) {
                    errorMsg('商品不存在');
                }

                if ($goods->is_group == 1) {
                    // 检查组合商品的子商品库存
                    if (empty($goods->goods_group)) {
                        errorMsg("组合商品[{$goods->goods_name}]配置错误");
                    }
                    $goodsGroups = json_decode($goods->goods_group, true);
//                    $subGoodsIds = explode(',', $goods->goods_group);
                    foreach ($goodsGroups as $goodsGroup) {
                        $subGoods = Goods::find($goodsGroup['id']);
                        if (!$subGoods) {
                            errorMsg("组合商品的子商品不存在");
                        }

                        // 检查子商品库存是否充足
                        if ($subGoods->goods_sale_num < $item['goods_num']) {
                            errorMsg("商品[{$subGoods->goods_name}]库存不足");
                        }
                    }
                } else {
                    // 普通商品库存检查
                    if ($goods->goods_sale_num < $item['goods_num']) {
                        errorMsg("商品[{$goods->goods_name}]库存不足");
                    }
                }
            }

            # 地址物流信息
            $express = Express::getInfoById($pamas['express_id']);
            $store = Store::where(['id' => $store_id])->first(['is_express_fee', 'discount_rate']);
            if ($store['is_express_fee'] == 1 && $pamas['order_province'] && $cartArr['goodsMoney'] < $express['order_money']) {
                $area_list = $express['area_list'];
                foreach ($area_list as $vv) {
                    if ($pamas['order_province'] == $vv['area_name']) {
                        // 使用之前已经获取的正确快递信息 $express
                        $result = $this->oneFreightAndAmount($cartArr['goods_list'], $express, $address['province'], $pamas['express_id'],$store_id);
                        if (isset($result['error'])) {
                            errorMsg($result['error']);
                        } else {
                            $express_fee = $result['freight'];
                        }
                    }
                }
            }
            // 调用统一计算逻辑
            $result = $this->calcAmountByGoodsList($cartArr['goods_list'], $express, $address['province'], $store_id);
            $pamas['goods_list'] = $cartArr['goods_list'];
            $pamas['goods_give_list'] = $cartArr['goods_give_list'];
            $pamas['order_amount'] = $result['original_amount']; //订单总金额
            $pamas['total_number'] = $cartArr['totalNum'];
            $pamas['goods_pay_amount'] = $result['order_amount']; //商品实付金
            $pamas['goods_amount'] = $result['goods_price_sum'];//商品总金额
            $pamas['freight'] = $result['freight'];
            $pamas['express_company'] = $express['express_name'];
            $pamas['order_status'] = 1;//未审核
            $pamas['order_status_reason'] = "已审核待发货";//审核原因
            // 判断订单是否免审核
            $nowTime = time();
            $currentHour = (int)date('G', $nowTime); // 保留这个变量，以防其他地方需要
            // 确保金额大于0且免审金额设置有效
            if ($pamas['order_amount'] > 0 && $storeInfo->avoid_review_amount > 0) {
                // 获取当前时间戳
                $currentTimestamp = time();

                // 处理开始时间（格式应为 Y-m-d H:i:s）
                $avoidReviewStartTime = $storeInfo->avoid_review_start_time;
                // 如果时间部分缺失，补全为 00:00:00
                if (strpos($avoidReviewStartTime, ':') === false) {
                    $avoidReviewStartTime .= ' 00:00:00';
                }
                $avoidReviewStartTimestamp = strtotime($avoidReviewStartTime);

                // 处理结束时间（格式应为 Y-m-d H:i:s）
                $avoidReviewEndTime = $storeInfo->avoid_review_end_time;
                // 如果时间部分缺失，补全为 23:59:59
                if (strpos($avoidReviewEndTime, ':') === false) {
                    $avoidReviewEndTime .= ' 23:59:59';
                }
                $avoidReviewEndTimestamp = strtotime($avoidReviewEndTime);

                // 验证时间格式是否正确
                if ($avoidReviewStartTimestamp === false || $avoidReviewEndTimestamp === false) {
                    // 记录错误日志或处理错误情况
                    error_log("Invalid avoid review time format: start={$storeInfo->avoid_review_start_time}, end={$storeInfo->avoid_review_end_time}");
                } else {
                    // 判断当前时间是否在免审时间范围内
                    $isInDateTimeRange = ($currentTimestamp >= $avoidReviewStartTimestamp &&
                        $currentTimestamp <= $avoidReviewEndTimestamp);

                    // 如果金额和时间范围都符合条件
                    if ($pamas['order_amount'] <= $storeInfo->avoid_review_amount && $isInDateTimeRange) {
                        $pamas['order_status'] = 2;
                        $pamas['order_status_reason'] = sprintf(
                            "订单金额 %.2f 元 ≥ 免审金额 %.2f 元，且在免审时段内（%s 至 %s）",
                            $pamas['order_amount'],
                            $storeInfo->avoid_review_amount,
                            date('Y-m-d H:i:s', $avoidReviewStartTimestamp),
                            date('Y-m-d H:i:s', $avoidReviewEndTimestamp)
                        );
                    }
                }
            }
            $order_id = StoreOrder::addInfoBySid($store_id, $pamas);
            if ($order_id) {
                //免审核直接进入订单同步队列
                if($pamas['order_status'] == 2) {
                    // 将订单数据写入Redis队列
                    $this->pushOrderToRedis($order_id, $store_id);
                }
                successMsg($order_id);
            }
        }
        errorMsg();
    }

    /**
     * 将订单数据写入Redis队列
     * @param int $order_id 订单ID
     * @param int $store_id 店铺ID
     * @return bool
     */
    private function pushOrderToRedis($order_id, $store_id)
    {
        try {
            // 获取订单详情
            $orderInfo = StoreOrder::getInfoById($order_id, $store_id);
            $goodsList = StoreOrderGoods::getListByOid($order_id, 1);
            $goodsListJson = json_encode($goodsList, JSON_UNESCAPED_UNICODE);
            Log::info('api pushOrderToRedis goodsListJson', [$goodsListJson]);
            $storeInfo = Store::find($store_id);
            //物流方式 圆通/中通5 顺丰8
            $logisticsType = 5;
            if ($orderInfo['express_id'] == 1) {
                $logisticsType = 5; //圆通/中通
            } elseif ($orderInfo['express_id'] == 2) {
                $logisticsType = 8; //顺丰速运
            } elseif ($orderInfo['express_id'] == 3) {
                $logisticsType = 88; //德邦
            }
            $order_time = date('Y-m-d H:i:s',$orderInfo['order_time']);

            $amountMoney = 0;
            // 构建旺店通订单数据
            $trade_list = [
                [
                    'tid' => $orderInfo['order_sn'], // 原始单号
                    'trade_status' => 30, // 30 待发货状态 50已发货(平台销售订单已经发货时推送此状态)，如果已发货在自建商城代表订单完结状态，无后续状态变更，直接推送状态值70。
                    'delivery_term' => 1, // 款到发货
                    'pay_status' => 2, // 已付款
                    'trade_time' => $order_time,
                    'pay_time' => $order_time,
                    'buyer_nick' => $storeInfo->store_name, // 客户网名
                    'receiver_name' => $orderInfo['order_name'],
                    'receiver_mobile' => $orderInfo['order_mobile'],
                    'receiver_province' => $orderInfo['order_province'],
                    'receiver_city' => $orderInfo['order_city'],
                    'receiver_district' => $orderInfo['order_area'],
                    'receiver_address' => $orderInfo['order_address'],
                    'logistics_type' => $logisticsType, // 物流方式 圆通/中通5 顺丰8 德邦88
                    'invoice_kind' => 0, // 不需要发票
                    'post_amount' => $orderInfo['freight'], // 邮费
//                    'paid' => $orderInfo['goods_amount']+$orderInfo['freight'], // 已付金额
                    'paid' => $orderInfo['freight'], // 已付金额
                    'cod_amount' => 0,
                    'ext_cod_fee' => 0,
                    'other_amount' => 0,
                    'order_list' => []
                ]
            ];

            // 处理商品数据，合并相同商品ID的记录
            $processedGoodsList = [];
            foreach ($goodsList as $goods) {
                // 使用goods_id和is_give组合作为唯一键
                $key = $goods['goods_id'];
                if (!isset($processedGoodsList[$key])) {
                    $processedGoodsList[$key] = $goods;
                } else {
                    // 累加商品数量和总金额
                    $processedGoodsList[$key]['goods_number'] += $goods['goods_number'];
                    $processedGoodsList[$key]['goods_amount'] += $goods['goods_amount'];

                    // 如果当前记录不是赠品而原记录是赠品，则替换价格
                    if ($goods['is_give'] == 0 && $processedGoodsList[$key]['is_give'] == 1) {
                        $processedGoodsList[$key]['goods_price'] = $goods['goods_price'];
                        $processedGoodsList[$key]['is_give'] = 0;
                    }
                }
            }
            $processedGoodsListJson = json_encode($processedGoodsList, JSON_UNESCAPED_UNICODE);
            Log::info('api pushOrderToRedis processedGoodsList', [$processedGoodsListJson]);
            // 重新索引数组
            $processedGoodsList = array_values($processedGoodsList);
            // 构建订单商品列表
            foreach ($processedGoodsList as $goods) {
                // 兜底查商品表
                if (empty($goods['goods_sn'])) {
                    $goodsInfo = \App\Models\Admin\Goods::find($goods['goods_id']);
                    if ($goodsInfo) {
                        if (empty($goods['goods_sn'])) $goods['goods_sn'] = $goodsInfo->goods_sn;
                    }
                }
                // goods_no和spec_no不能同时为空
                if (empty($goods['goods_sn'])) {
                    continue; // 跳过这个商品，或者报错
                }
                $goods_price = $goods['goods_price_yu'] ?? 0;
                if ($goods['is_give'] == 1) {
                    $goods_price =  0;
                }
                $goods_price = 0;
                $amountMoney += $goods_price * $goods['goods_number'];
                $trade_list[0]['order_list'][] = [
                    'oid' => $orderInfo['order_sn'] . time(). $goods['goods_id'],
                    'status' => 30,
                    'refund_status' => 0,
                    'goods_id' => $goods['goods_id'],
                    'spec_id' => $goods['spec_id'] ?? '',
                    'goods_no' => $goods['goods_sn'] ?? '',
                    'spec_no' => $goods['goods_sn']. "_" . $goods['goods_unit'] . "_" . $goods['goods_specification'] ?? '', // spec_no优先，没有就用goods_sn兜底 规格编码
                    'goods_name' => $goods['goods_name'],
                    'spec_name' => $goods['goods_specification'] ?? '',//平台规格名称
                    'num' => $goods['goods_number'],
                    'price' => $goods_price,
                    'adjust_amount' => 0,
                    'discount' => 0,
                    'share_discount' => 0,
                    'cid' => $goods['cate_id'] ?? ''
                ];
            }

            $trade_list[0]['paid'] =  $amountMoney +$orderInfo['freight']; // 已付金额 订单总金额+运费

            $infoArr = json_encode([
                'trade' => $trade_list[0],
                'order_list' => $trade_list[0]['order_list']
            ], JSON_UNESCAPED_UNICODE);
            Log::info('api 订单写入Redis队列order:pending:push', [$infoArr]);
            // 将订单数据写入Redis队列
            Redis::rpush('order:pending:push', $infoArr);

            return true;
        } catch (\Exception $e) {
            \Log::error('api 订单写入Redis队列失败', [
                'order_id' => $order_id,
                'error' => $e->getMessage()
            ]);
            return false;
        }
    }

    /**
     *发货订单列表
     */
    public function orderList()
    {
        $type = $this->requestArr['type'] ?: 1;
        $store_id = $this->userArr['store_id'];
        $list = StoreOrder::getPageList($store_id, $type);
        successMsg($list);
    }

    /**
     * 订单详情
     */
    public function orderDetail()
    {
        $order_id = $this->requestArr['order_id'];
        $store_id = $this->userArr['store_id'];
        if ($order_id) {
            $orderInfo = StoreOrder::getInfoById($order_id, $store_id);
            if ($orderInfo) {
                $info['orderInfo'] = $orderInfo;
                $info['goodsList'] = StoreOrderGoods::getListByOid($order_id, 1);
                $info['goodsGiveList'] = StoreOrderGoods::getListByOid($order_id, 2);
                successMsg($info);
            }
            errorMsg('订单不存在');
        }
        errorMsg();
    }

    // 订单PDF打印
    public function orderPdf()
    {
        $params = $this->requestArr;
        if ($params['id']) {
            $info = \App\Models\Admin\StoreOrder::getInfoById($params['id']);
            if ($info) {
                $goodsList = \App\Models\Admin\StoreOrderGoods::getListByOid($params['id']);
                $total = [];
                foreach ($goodsList as $item) {
                    $total['num'] += $item['goods_number'];
                    if ($item['is_give'] == 0) {
                        $total['goods_price_yu'] += $item['goods_price_yu'];
                        $total['goods_price_zn'] += $item['goods_price_yu'] * $item['goods_number'];
                    }
                }
                $storeInfo = \App\Models\Admin\Store::getInfoById($info['store_id']);
                $info['subsidiary'] = $storeInfo['subsidiary'] ?? "亿恩鑫（上海）生物科技有限公司";
                $html = view('admin/order/orderPdf', ['data' => $info, 'storeInfo' => $storeInfo, 'goodsList' => $goodsList, 'total' => $total]);
                $pdf = new PrPdf();
                $pdf->makePdfByHtml($storeInfo['subsidiary'], $info['order_sn'], $html, 3);
                $fullDomain = request()->getSchemeAndHttpHost();
//                $filePath = storage_path("app/uploads/pdf/order/{$info['order_sn']}.pdf");
//                if (file_exists($filePath)) {
//                    unlink($filePath); // 删除旧文件
//                }
                $time = time();
                successMsg($fullDomain . "/uploads/pdf/order/{$info['order_sn']}.pdf"."?t=".$time);
            }
        }
        errorMsg();
    }

    public static function calculateGroupStock($goods)
    {
        if (empty($goods->goods_group)) {
            return 0;
        }

        $subGoodsIds = explode(',', $goods->goods_group);
        $minStock = PHP_INT_MAX;

        foreach ($subGoodsIds as $subGoodsId) {
            $subGoods = self::find($subGoodsId);
            if (!$subGoods) {
                continue;
            }
            $minStock = min($minStock, $subGoods->goods_sale_num);
        }

        return $minStock == PHP_INT_MAX ? 0 : $minStock;
    }

    /**
     * 组装商品信息
     */
    private function assembleGoodsInfo($goods_info_arr_from_request)
    {
        $goods_info_arr = [];
        $goods_give_list = [];
        
        if (!empty($goods_info_arr_from_request)) {
            foreach ($goods_info_arr_from_request as $item) {
                $goods_id = $item['goods_id'] ?? 0;
                $goods_num = $item['goods_num'] ?? 0;
                $is_give = $item['is_give'] ?? 0;
                $goods_weight_m = floatval($item['goods_weight_m'] ?? 1); // 默认1kg

                if ($goods_id && $goods_num >= 1) {
                    $goods_data = [
                        'goods_id' => $goods_id,
                        'goods_num' => $goods_num,
                        'goods_weight_m' => $goods_weight_m
                    ];
                    
                    if ($is_give == 1) {
                        $goods_give_list[] = $goods_data;
                    } else {
                        $goods_info_arr[] = $goods_data;
                    }
                } else {
                    errorMsg('商品信息不完整或数量错误');
                }
            }
        }
        
        return [
            'goods_info_arr' => $goods_info_arr,
            'goods_give_list' => $goods_give_list
        ];
    }

    /**
     * 根据商品列表、快递、省份，计算金额与运费
     * @param array $goods_list [{goods_id, goods_num, is_give?, goods_pid?}]
     * @param array $express 快递信息（含 area_list）
     * @param string $province 收货省
     * @param integer $store_id 商家id
     * @return array ['goods_list' => [...], 'order_amount' => ..., 'freight' => ..., 'original_amount' => ...]
     */
    private function calcAmountByGoodsList($goods_list, $express, $province, $store_id)
    {
        $sum_weight = 0;
        $goods_detail = [];
        $order_amount = 0; // 商品*商品数量*折扣率
        $goods_price_sum = 0; // 折扣前总金额
        $payGoodNum = 0;//商品数量
        foreach ($goods_list as $item) {
            $good_id = $item['goods_id'] ?? 0;
            $num = $item['goods_num'] ?? 0;
            $goods_pid = $item['goods_pid'] ?? 0;
            $goods_group = $item['goods_group'] ?? "";
            if (!$good_id || !$num) continue;

            $good = \App\Models\Admin\Goods::find($good_id);
            if (!$good) continue;
            $goodsInfo = GoodsStore::getOrderByGoodsId($store_id, $good_id, $num);
            $price = floatval($goodsInfo['sale_price']);
            $weight = floatval($good['goods_weight_m']);
            $is_give = $item['is_give'] ?? 0;
            
            // 如果是赠送商品则不计算金额和重量
            if ($is_give == 1) {
                $goods_detail[] = [
                    'goods_id' => $good_id,
                    'goods_name' => $good['goods_name'],
                    'goods_price' => 0, // 赠品价格为0
                    'goods_num' => $num,
                    'goods_group' => $goods_group,
                    'goods_weight_m' => $weight,
                    'total_price' => 0,
                    'is_give' => 1 // 标记为赠品
                ];
                // 修改：赠品也需要计入商品数量
                $payGoodNum += $num;
                continue;
            }

            // 处理组合商品逻辑：如果goods_pid不为0，说明这是组合商品的子商品，跳过价格计算
            if ($goods_pid != 0) {
                // 组合商品的子商品，只计算重量，不计算价格
                $sum_weight += $weight * $num;
                $goods_detail[] = [
                    'goods_id' => $good_id,
                    'goods_name' => $good['goods_name'],
                    'goods_price' => $price,
                    'goods_num' => $num,
                    'goods_group' => $goods_group,
                    'goods_weight_m' => $weight,
                    'total_price' => 0, // 子商品不单独计算价格
                    'is_give' => 0,
                    'goods_pid' => $goods_pid // 标记为子商品
                ];
                // 修改：如果goods_pid不为0，说明是组合商品子项，需要计入商品数量
                $payGoodNum += $num;
                continue;
            }

            // 修改：type判断逻辑移除，直接累加单商品数量
            if ($item['type'] == 1) {
                $payGoodNum += $num;
            }

            
            // 普通商品或组合商品主商品：正常计算价格和重量
            $original_item_total_price = $price * $num; // 单品折扣前总价
            $sum_weight += $weight * $num;
            $order_amount += $original_item_total_price;
            $goods_price_sum = $goods_price_sum + $price * $num;

            $goods_detail[] = [
                'goods_id' => $good_id,
                'goods_name' => $good['goods_name'],
                'goods_price' => $price,
                'goods_num' => $num,
                'goods_group' => $goods_group,
                'goods_weight_m' => $weight,
                'total_price' => round($original_item_total_price, 2),
                'is_give' => 0, // 标记为非赠品
                'goods_pid' => $goods_pid // 标记为子商品
            ];
        }

        if ($sum_weight <= 0) {
            return ['error' => '商品重量异常'];
        }

        // 运费计算
        $area_list = $express['area_list'] ?? [];
        $first_unit = 0;
        $two_unit = 0;

        foreach ($area_list as $area) {
            if ($area['area_name'] == $province) {
                $first_unit = $area['first_unit'];
                $two_unit = $area['two_unit'];
                break;
            }
        }

        if ($first_unit === 0) {
            return ['error' => '未配置该省份运费'];
        }

        $freight = $first_unit;
        if ($sum_weight > 1) {
            $extra_weight = ceil($sum_weight - 1);
            $freight += $extra_weight * $two_unit;

            if (strpos($express['express_name'], '顺丰') !== false) {
                $freight += 2;
            }
        }
        // 修改：将die()改为正常返回
        // var_dump($payGoodNum);die();
        return [
            'goods_list' => $goods_detail,
            'freight' => round($freight, 2),
            'goods_price_sum' => round($goods_price_sum, 2),
            'order_amount' => round($order_amount, 2),
            'original_amount' => round($order_amount + $freight, 2),
            'num' => $payGoodNum // 修改：将$pay_num改为$payGoodNum
        ];
    }

    /**
     * 计算运费和订单金额（可复用）
     * @param array $goods_info_arr 商品数组 [{good_id, num}]
     * @param array $expressList 已查到的快递公司信息
     * @param string $province 收货省份
     * @param string $expressId 物流id
     * @return array ['freight'=>..., 'order_amount'=>...]
     */
    /**
     * 简化版本：调用统一运费和金额计算逻辑
     * @param array $goods_info_arr 商品数组 [{good_id, num, goods_pid?}]
     * @param array $expressList 当前快递公司信息
     * @param string $province 省份
     * @param int $expressId 快递ID
     * @return array ['freight'=>..., 'order_amount'=>...]
     */
    private function oneFreightAndAmount($goods_info_arr, $expressList, $province, $expressId,$store_id)
    {
        // 整理为 calcAmountByGoodsList 的格式：每项包含 goods_id、goods_num 和 goods_pid
        $formatted_goods_list = [];
        foreach ($goods_info_arr as $item) {
            $formatted_goods_list[] = [
                'goods_id' => $item['goods_id'],
                'goods_num' => $item['goods_num'],
                'goods_pid' => $item['goods_pid'] ?? 0 // 保留goods_pid信息
            ];
        }

        // 默认折扣为 1.0（不打折）
        $discount = 1.0;

        // 调用统一计算方法
        $result = $this->calcAmountByGoodsList($formatted_goods_list, $expressList, $province, $store_id);

        if (isset($result['error'])) {
            return ['error' => $result['error']];
        }

        return [
            'freight' => $result['freight'],
            'order_amount' => $result['order_amount']
        ];
    }


}